package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.ex.ServiceCode;
import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.mapper.AlbumMapper;
import cn.tedu.csmall.product.mapper.PictureMapper;
import cn.tedu.csmall.product.pojo.dto.PictureAddNewDTO;
import cn.tedu.csmall.product.pojo.entity.Picture;
import cn.tedu.csmall.product.pojo.vo.AlbumStandardVO;
import cn.tedu.csmall.product.service.IPictureService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class PictureServiceImpl implements IPictureService {

    @Autowired
    PictureMapper pictureMapper;
    @Autowired
    AlbumMapper albumMapper;
    /**
     * 插入一条照片数据
     * @param pictureAddNewDTO
     */
    @Override
    public void addNew(PictureAddNewDTO pictureAddNewDTO) {
        //获取照片数据的相册id
        Long albumId=pictureAddNewDTO.getAlbumId();
        //通过相册id获取相册对象
        AlbumStandardVO albumStandardVO = albumMapper.getAlbumStandardVO(albumId);
        //如果对象为null，抛出异常
        if(albumStandardVO==null){
            String message="添加失败，对应的相册不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        //如果存在，创建照片对象，把DTO对象复制到照片对象中
        Picture picture=new Picture();
        BeanUtils.copyProperties(pictureAddNewDTO,picture);
        //调用mapper接口的insert方法插入照片数据
        int rows = pictureMapper.insert(picture);
        //如果受影响行数不等于1
        if(rows!=1){
            String message="添加失败，系统异常，请稍后重试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        log.debug("添加成功！");
    }

    /**
     * 根据id删除一条照片数据
     * @param id
     */
    @Override
    public void delete(Long id) {
        //根据id查询照片表数据数量
        int countById = pictureMapper.countById(id);
        if(countById!=1){
            String message="删除失败，该照片不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        //数据存在，调用mapper接口的delete方法
        int rows = pictureMapper.deleteById(id);
        //如果受影响行数不等于1，抛出异常
        if(rows!=1){
            String message="删除失败，系统异常，请稍后重试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
        log.error("删除照片成功！");
    }
}
